package prassein.rsm.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.util.ServletContextAware;
import org.springframework.beans.factory.annotation.Autowired;

import prassein.rsm.common.utils.Constants;
import prassein.rsm.entity.base.Audit;
import prassein.rsm.service.base.AuditManager;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Results({
	@Result(name = "success",location="auditList.jsp"), 
	@Result(name = "error",location="login.jsp"),
	@Result(name = "input",location="auditList.jsp")})
public class AuditListAction extends ActionSupport implements ServletContextAware {
	
	private static final long serialVersionUID = -2357171560892244028L;

	@Autowired
	private AuditManager auditManager;
	
	private ServletContext context;
	
	public int totalCount = 0;
	
	private int page;
	private int pageSize;
	
	private List<Audit> auditList;
	
	@Override 
	public String execute() throws Exception {
		Map<String, Object> session = ActionContext.getContext().getSession();
		if (session.get(Constants.USERNAME) != null && !session.get(Constants.USERNAME).equals("")) {
			String res = SUCCESS;
			
			res = ListAllResume(session);
			
			return res;
		} else {
			return ERROR;
		}
	}
	
	private String ListAllResume(Map<String, Object> session) {
		List<Audit> listTemp = auditManager.getAudits();
		
		totalCount = listTemp.size();
		
		auditList = new ArrayList<Audit>();
		
		int from = page * pageSize;
		int to = from + pageSize;
		if (to > totalCount) {
			to = totalCount;
		}
		for (int i = from; i < to; i++) {
			auditList.add(listTemp.get(i));
		}
		
		return SUCCESS;
	}
	
	public int getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	@Override
	public void setServletContext(ServletContext context) {
		this.context = context;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public AuditManager getAuditManager() {
		return auditManager;
	}
	public void setAuditManager(AuditManager auditManager) {
		this.auditManager = auditManager;
	}

	public List<Audit> getAuditList() {
		return auditList;
	}

	public void setAuditList(List<Audit> auditList) {
		this.auditList = auditList;
	}
}
